// 接接口的商品列表
export const productList = (editor) => {
    const { Components } = editor;
    Components.addType('productList', {
        model: {
            defaults: {
                name: 'productList',
                droppable: true,
                components: [{
                    type: 'div',
                    attributes: {
                        class: 'container'
                    },
                    components: [{
                        type: 'div',
                        attributes: {
                            class: 'containerTop'
                        }
                    },
                    {
                        type: 'div',
                        attributes: {
                            class: 'containerBottom'
                        }
                    },
                    ]
                }],
                script() {
                    var th = document.getElementById(this.id);
                    let listDiv = th.getElementsByClassName('containerTop')[0];
                    let listDivBottom = th.getElementsByClassName('containerBottom')[0];
                    let total = 0; // 总条数
                    let current = 1; // 当前页码
                    let range = 5; // 页码范围
                    let allPages = 0; // 总页数
                    // 更新商品列表
                    function refresh(current) {
                        var setting = "http://home.i3vsoft.com:1080//shopping-mall-backend/sp/product/list";
                        listDiv.innerHTML = '';
                        listDivBottom.innerHTML = '';
                        if (setting) {
                            fetch(setting, {
                                method: 'POST',
                                headers: {
                                    'X-SYSTEM': 'saas',
                                    'X-Access-Token': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpblR5cGUiOjEsImV4cCI6MTcyNTU0MTYyNCwicGxhdGZvcm0iOjIsInVzZXJuYW1lIjoiMTM1MzUwNDgzOTcifQ.bao09FBDYdub_dluXm47LwpIfakvaL53SiT468O6TY0&username=13535048397&tenantId=ff80808188dd574e0188fa8094cf0259',
                                    'Content-Type': 'application/json'
                                },
                                body: JSON.stringify({
                                    'pageNo': current,
                                    'pageSize': 8,
                                    'shopId': '2c9616b68634e19f018634eeefec010c'
                                })
                            }).then(res => {
                                if (res.ok) {
                                    return res.json();
                                }
                            }).then(data => {
                                total = data.result.total;
                                allPages = 0;
                                allPages += total / 8;
                                if (total % 8 > 0) allPages++; // 没满8个算一页
                                const listData = data.result.records;
                                let count = 0;
                                let rowData = [];
                                listData.forEach(item => {
                                    count++;
                                    rowData.push(item);
                                    if (count % 4 == 0 || count == listData.length) {
                                        const rowDiv = document.createElement('div');
                                        rowDiv.style.width = '100%';
                                        rowDiv.style.display = 'flex';
                                        rowData.forEach(rowItem => {
                                            const singleDiv = document.createElement('div');
                                            singleDiv.style.width = '23%';
                                            singleDiv.style.height = '280px';
                                            singleDiv.style.margin = '1%';
                                            singleDiv.style.border = '1px solid gray';
                                            singleDiv.style.display = 'flex';
                                            singleDiv.style.borderRadius = '5px';
                                            singleDiv.style.flexDirection = 'column';
                                            singleDiv.innerHTML = `
                                    <div style="width:94%;height:55%;background-color:gray;margin:3%;"></div>
                                    <span style="margin-left:3%;font-size:16px;"> ${rowItem.commodityName} </span>
                                    <span style="margin-left:3%;font-size:12px;margin:5% 3%;color:gray;"> ${rowItem.details} </span>
                                    <span style="margin-left:3%;font-size:22px;margin:5% 3%;color:red;font-weight:bold;"> ${rowItem.commodityPrice} </span>
                                    `
                                            singleDiv.addEventListener('click',() => skip(rowItem))
                                            rowDiv.appendChild(singleDiv);
                                        })
                                        rowData = [];
                                        count = 0;
                                        listDiv.appendChild(rowDiv);
                                    }
                                });
                                updataPage(current);
                            })
                        }
                    }
                    refresh(current);
                    // 展示底部页码
                    function updataPage() {
                        listDivBottom.style.display = 'flex';
                        listDivBottom.style.justifyContent = 'space-between';
                        const dataSpan = document.createElement('span');
                        dataSpan.style.margin = '3% 2%';
                        dataSpan.style.fontSize = '14px';
                        dataSpan.innerHTML = `共${total}个商品，当前展示数量8`;
                        const pagDiv = document.createElement('div');
                        pagDiv.style.margin = '3% 2%';
                        pagDiv.style.fontSize = '14px';
                        pagDiv.style.display = 'flex';
                        pagDiv.style.textAlign = 'center';
                        const leftDiv = document.createElement('div');
                        leftDiv.style.width = '30px';
                        leftDiv.style.height = '30px';
                        leftDiv.style.border = '1px solid black';
                        leftDiv.innerHTML = `<`;
                        leftDiv.addEventListener('click', () => {
                            prevPage();
                        })
                        pagDiv.appendChild(leftDiv);
                        updatePageRange().forEach(item => {
                            const div = document.createElement('div');
                            div.style.width = '30px';
                            div.style.height = '30px';
                            div.style.border = '1px solid black';
                            div.innerHTML = `${item}`
                            pagDiv.appendChild(div);
                        })
                        const rightDiv = document.createElement('div');
                        rightDiv.style.width = '30px';
                        rightDiv.style.height = '30px';
                        rightDiv.style.border = '1px solid black';
                        rightDiv.innerHTML = `>`;
                        rightDiv.addEventListener('click', () => {
                            nextPage();
                        })
                        pagDiv.appendChild(rightDiv);
                        listDivBottom.appendChild(dataSpan);
                        listDivBottom.appendChild(pagDiv);
                    }

                    function updatePageRange() {
                        let start = Math.max(1, current - Math.floor((range - 1) / 2)); // 向前取整，但不超过1  
                        let end = Math.min(allPages, current + Math.ceil((range - 1) / 2)); // 向后取整，但不超过allPages  

                        // 如果因为靠近开始或结束而范围不足5个页码，则不需要调整（因为已经是最大可能范围）  

                        // 修正start和end，确保它们不会超出总页数的范围  
                        start = Math.max(1, start); // 确保start不小于1  
                        if (current < allPages) {
                            end = Math.min(allPages, end); // 确保end不大于allPages  
                        } else {
                            alert("已经到最后！")
                            end = current - 1;
                        }
                        return Array.from({ length: end - start + 1 }, (_, i) => start + i);
                    }

                    // 向前按钮
                    function prevPage() {
                        if (current > 1) {
                            current--;
                            refresh(current);
                        }
                    }

                    // 向后按钮
                    function nextPage() {
                        if (++current > allPages) current--;
                        refresh(current);
                    }

                    // 页面跳转传递参数
                    function skip(data){
                        sessionStorage.setItem('id', data.id);
                        sessionStorage.setItem('name', data.commodityName); 
                        window.open('/index3.html','_blank');
                    }
                },
                styles: `
                body,html{
                    width: 100%;
                    height: 100%;
                    margin: 0;
                }
                .container{
                    width: 100%;
                    height: 100vh;
                    display: flex;
                    flex-direction: column;
                }
                .containerTop{
                    width: 100%;
                    height: 85%;
                }
                .containerBottom{
                    width: 100%;
                    height: 15%;
                }
              `,
            },
        },
    });
    editor.BlockManager.add("productList", {
        label: "商品列表",
        category: "首页组件",
        media: `<svg t="1725329942726" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5159" width="25" height="25"><path d="M853.333333 0H170.666667a170.666667 170.666667 0 0 0-170.666667 170.666667v682.666666a170.666667 170.666667 0 0 0 170.666667 170.666667h682.666666a170.666667 170.666667 0 0 0 170.666667-170.666667V170.666667a170.666667 170.666667 0 0 0-170.666667-170.666667zM170.666667 113.777778h682.666666a56.888889 56.888889 0 0 1 56.888889 56.888889v65.422222H113.777778V170.666667a56.888889 56.888889 0 0 1 56.888889-56.888889z m682.666666 796.444444H170.666667a56.888889 56.888889 0 0 1-56.888889-56.888889V344.177778h796.444444v512a56.888889 56.888889 0 0 1-56.888889 54.044444z" p-id="5160"></path><path d="M766.293333 672.426667H431.217778a54.044444 54.044444 0 1 0 0 108.088889h335.075555a56.888889 56.888889 0 0 0 0-108.088889zM299.804444 670.151111h-33.564444a54.044444 54.044444 0 0 0 0 108.088889h33.564444a54.044444 54.044444 0 0 0 0-108.088889zM766.293333 472.746667H431.217778a54.044444 54.044444 0 1 0 0 108.088889h335.075555a54.044444 54.044444 0 0 0 0-108.088889zM299.804444 470.471111h-33.564444a56.888889 56.888889 0 0 0 0 108.088889h33.564444a56.888889 56.888889 0 0 0 0-108.088889z" p-id="5161"></path></svg>`,
        select: true,
        content: { type: "productList" },
    });
}